const initModels = require("../../models");
const bcrypt = require("bcrypt");

exports.register = async function (req, res) {
  try {
    // 加密密码
    const hashedPassword = await bcrypt.hash(req.body.password, 10);
    console.log(hashedPassword, 'hashedPassword');
    // 在数据库中创建新用户
    const user = await initModels.mytable.create({
      name: req.body.name,
      password: hashedPassword,
    });

    // 返回成功响应
    res.status(201).json({ success: true, status: 200, message: '注册成功！', user });
  } catch (error) {
    // 返回错误响应
    res.status(500).json({ success: true, status: 500, error: error.message });
  }
};

exports.login = async function (req, res) {
  try {
    const user = await initModels.mytable.findOne({ where: { name: req.body.name } });
    if (!user) {
      return res.status(401).json({ success: true, status: 401, error: "未找到用户." });
    }
    const isMatch = await bcrypt.compare(req.body.password, user.password);
    console.log(user.password, req.body.password, req.body.password === user.password, isMatch, 'useruser');
    if (!isMatch) {
      return res.status(401).json({ success: true, status: 401, error: "密码不正确." });
    }

    res.json({ success: true, status: 200, message: "用户登录成功." });
  } catch (error) {
    // 返回错误响应
    res.status(500).json({ success: true, status: 500, error: error.message });
  }
};